<?php

use Illuminate\Support\Facades\Cache;
use Illuminate\Contracts\Cache\Lock;

/**
 * 生成锁缓存内容
 */
function apiCacheToken($lock_str_title)
{
    $token = md5(time());
    Cache::put('api_cache_token' . $lock_str_title, $token);
    return $token;
}
/**
 * 校验锁缓存内容
 */
function checkApiCacheToken($lock_str_title, $token)
{
    $cache_token = Cache::get('api_cache_token' . $lock_str_title);
    return $cache_token == $token;
}
/**
 * 锁缓存内容锁定
 */
function lockApiCacheToken($lock_str_title, $time = 20)
{
    $lock = Cache::lock('api_cache_token' . $lock_str_title, $time);
    return $lock;
}

/**
 * 锁释放
 */
function lockReleaseApiCacheToken(Lock $lock)
{
    $lock->release();
}

/**
 * 锁内容删除
 */
function delApiCacheToken($lock_str_title)
{
    Cache::forget('api_cache_token' . $lock_str_title);
}

/**
 * 获取客户端ip
 */
function getClientIp($type = 0, $adv = false)
{
    $type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos    =   array_search('unknown', $arr);
            if (false !== $pos) unset($arr[$pos]);
            $ip     =   trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip     =   $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * 资源文件获取完整链接获取
 */
function toMedia($src)
{
    $src = trim($src);
    if (empty($src)) {
        return '';
    }

    if (('http://' == substr($src, 0, 7)) || ('https://' == substr($src, 0, 8))) {
        return $src;
    } else {
        return env('APP_URL') . $src;
    }
}

/**
 * 获取随机字符串
 */
function getRandomString($len = 12, $chars = null)
{
    if (is_null($chars)) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    }
    mt_srand(10000000 * (float)microtime());
    for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; ++$i) {
        $str .= $chars[mt_rand(0, $lc)];
    }
    return $str;
}

/**
 * 框架分页，格式转换
 */
function paginateDataToArray($data)
{
    $newdata = [
        'list' => $data['data'],
        'page' => [
            'totalCount' => $data['total'],
            'currentPage' => $data['current_page'],
            'totalPage' => $data['last_page']
        ]
    ];
    return $newdata;
}

/**
 * 设置提示语
 */
function getMsgByCode($code)
{
    $codeToMsg = [
        '000' => '操作成功',
        '400' => '登录失效',
        '001' => '无效参数',
        '002' => '非法访问',
    ];

    return isset($codeToMsg[$code]) ? $codeToMsg[$code] : '';
}

/**
 * 数据计算方式
 *
 * @param [type] $act  add、sub、mul、div
 * @param [type] $num1
 * @param [type] $num2
 * @param integer $scale 保留小数位数
 * @param integer $numtype 0精度计算、1四舍五入
 */
function mathfunc($act, $num1, $num2, $scale = 0, $numtype = 0)
{

    $funcname = 'bc' . $act;
    if (function_exists($funcname)) {

        if ($numtype == 0) {
            return $funcname($num1, $num2, $scale);
        } else {
            //return number_format(round($funcname($num1, $num2, ($scale + 1)), $scale), $scale);
            return number_format(round($funcname($num1, $num2, ($scale + 1)), $scale), $scale,'.','');
        }
    } else {
        throw new \Exception('无效计算方式');
    }
}

/**
 * 重量计算方式
 *
 * @param [type] $act  add、sub、mul、div
 * @param [type] $num1
 * @param [type] $num2
 * @param integer $scale 保留小数位数
 */
function mathfuncweight($act, $num1, $num2, $scale = 0)
{

    $funcname = 'bc' . $act;
    if (function_exists($funcname)) {

        if (env('MATHTYPEWITHWEIGHT') == 0) {
            return $funcname($num1, $num2, $scale);
        } else {
//            return number_format(round($funcname($num1, $num2, ($scale + 1)), $scale), $scale);
            return number_format(round($funcname($num1, $num2, ($scale + 1)), $scale), $scale,'.','');
        }
    } else {
        throw new \Exception('无效计算方式' . $funcname);
    }
}

/**
 * 金额计算方式
 *
 * @param [type] $act  add、sub、mul、div
 * @param [type] $num1
 * @param [type] $num2
 * @param integer $scale 保留小数位数
 */
function mathfuncmoney($act, $num1, $num2, $scale = 0)
{

    $funcname = 'bc' . $act;
    if (function_exists($funcname)) {

        if (env('MATHTYPEWITHMONEY') == 0) {
            return $funcname($num1, $num2, $scale);
        } else {
            //return number_format(round($funcname($num1, $num2, ($scale + 1)), $scale), $scale);
            return number_format(round($funcname($num1, $num2, ($scale + 1)), $scale), $scale,'.','');
        }
    } else {
        throw new \Exception('无效计算方式');
    }
}

/**
 * 计算采购单重--待定
 *
 * @param [type] $archive_spec
 * @param [type] $type
 * @param integer $length
 */
function mathtoweightbyarchivetype($archive_spec, $type, $length = 0)
{
    $archive_spec_arr = explode('*', $archive_spec);
    if ($type == 1 && count($archive_spec_arr) >= 2 && $length > 0) { //理计
        //返回吨
        // return mathfuncweight('div',mathfuncweight('mul',mathfuncweight('mul',intval($archive_spec_arr[0])*intval($archive_spec_arr[1]),$length,4),env('DENSITY'),4),1000,4);
        //返回kg
//        return mathfuncweight('mul', mathfuncweight('mul', intval($archive_spec_arr[0]) * intval($archive_spec_arr[1]), $length, 1), env('DENSITY'), 1);
        //修改为3位小数计算 2025-10-24
        return mathfuncweight('mul', mathfuncweight('mul', intval($archive_spec_arr[0]) * intval($archive_spec_arr[1]), $length, 1), env('DENSITY'));
    } elseif ($type == 3 && count($archive_spec_arr) == 3) { //定尺
        //返回吨
        // return mathfuncweight('div',mathfuncweight('mul',mathfuncweight('mul',intval($archive_spec_arr[0])*intval($archive_spec_arr[1]),intval($archive_spec_arr[2]),4),env('DENSITY'),4),1000,4);
        //返回kg
//        return mathfuncweight('mul', mathfuncweight('mul', intval($archive_spec_arr[0]) * intval($archive_spec_arr[1]), intval($archive_spec_arr[2]), 1), env('DENSITY'), 1);
        //修改为3位小数计算 2025-10-24
        return mathfuncweight('mul', mathfuncweight('mul', intval($archive_spec_arr[0]) * intval($archive_spec_arr[1]), intval($archive_spec_arr[2]), 1), env('DENSITY'));
    } else {
        throw new \Exception('无效码单类型');
    }
}

/**
 * 验签
 */
function checkformsign($params)
{
    ksort($params);
    $paramString = '';
    foreach ($params as $key => $value) {
        if (is_null($value) || $value == '' || $key == 'sign') {
            continue;
        }
        // if (is_array($value) && count($value) <= 0) {
        //     continue;
        // }
        if (is_array($value)) {
            $value = json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            // $value=json_encode($value);
        }
        $paramString .= $key . '=' . $value . '&';
    }
    if ($paramString == '') {
        return true;
    }
    $paramString = $paramString . 'key=' . env('SITESIGNKEY');
    $sign = md5($paramString);
    if (!isset($params['sign'])) {
        return false;
    }
    // Log::info($paramString);
    // Log::info($sign);
    // echo $sign;exit;
    return $params['sign'] == $sign;
}

function showMonthRange($start, $end)
{
    // 转换为月
    $end = date('Y-m', strtotime($end));
    $range = [];
    $i = 0;
    do {
        $month = date('Y-m', strtotime($start . ' + ' . $i . ' month'));
        //echo $i . ':' . $month . '<br>';
        $range[] = $month;
        $i++;
    } while ($month < $end);

    return $range;
}
function isTimestamp($v) {
    return is_numeric($v) && (int)$v == $v && strlen((string)$v) === 10;
}
